<template>
  <el-dialog
    :close-on-click-modal="false"
    title="定损详情"
    :visible="detailsVisible"
    :before-close="onClose"
    :style="{ 'max-height': '100vh' }"
    width="90%"
  >
    <div style="max-height: 70vh; overflow-y: auto">
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="案件号：">{{ form.case_number }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物损方及电话:">{{
              form.damage_customer
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="查勘员:">{{ form.surveyer }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物损方确定报价:">{{
              form.damage_customer_price
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="施工费用:">{{
              form.construction_amount || "暂无"
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率:">{{ form.tax_rate + "%" }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="税金:">{{
              form.taxes || "暂无"
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="施工总价:">{{
              form.total_amount || "暂无"
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="36">
            <el-form-item class="item" label="物损项目:">
              <el-button @click="addInput" size="mini" type="primary"
                >新增</el-button
              >
              <el-button
                :disabled="damageData.length === 0"
                @click="Export"
                size="mini"
                type="warning"
                v-hasPermi="['system:assessManagement:export']"
                >导出</el-button
              >
              <el-checkbox
                style="margin-left: 10px"
                v-model="flag"
                :true-label="1"
                :false-label="0"
                @change="handleFlagChange"
                >是否盖章</el-checkbox
              >
            </el-form-item>
            <div
              v-for="(itm, index) in damageData"
              :key="index"
              style="
                margin: 10px 0;
                display: flex;
                align-items: center;
                flex-wrap: wrap;
              "
            >
              <i style="font-style: normal">名称:</i>
              <el-input
                placeholder="请输入名称"
                style="width: 120px; margin-left: 5px"
                v-model="itm.damage_project_name"
              ></el-input>
              <i style="font-style: normal; margin-left: 10px">数量:</i>
              <el-input-number
                style="width: 120px; margin-left: 5px"
                v-model="itm.damage_project_number"
                :min="1"
                :max="10000"
              ></el-input-number>
              <i style="font-style: normal; margin-left: 10px">单位:</i>
              <el-input
                placeholder="请输入单位"
                style="width: 110px; margin-left: 5px"
                v-model="itm.unit"
              ></el-input>
              <i style="font-style: normal; margin-left: 10px">报价:</i>
              <el-input
                placeholder="请输入报价"
                style="width: 120px; margin-left: 5px"
                v-model="itm.damage_project_price"
              ></el-input>
              <i style="font-style: normal; margin-left: 10px">总价:</i>
              <el-input
                disabled
                style="width: 120px; margin-left: 5px"
                v-model="itm.total_project_price"
              ></el-input>
              <i style="font-style: normal; margin-left: 10px">备注:</i>
              <el-input
                type="textarea"
                placeholder="请输入备注"
                style="width: 150px; margin-left: 5px"
                v-model="itm.remarks"
              ></el-input>
              <i style="font-style: normal; margin-left: 10px">图片:</i>
              <el-upload
                class="load"
                action="#"
                :on-preview="handlePreview"
                :http-request="(param) => uploadImage(param, index)"
                :on-change="
                  (file, fileList) => handleChangeImg(file, fileList, index)
                "
                :on-remove="
                  (file, fileList) => handleRemove(file, fileList, index)
                "
                :show-file-list="false"
                :file-list="fileList"
                multiple
                style="margin-left: 5px"
              >
                <el-button type="primary" size="mini">上传</el-button>
              </el-upload>
              <div
                v-for="(item, imgIndex) in itm.imgList"
                :key="imgIndex"
                style="position: relative"
              >
                <el-image
                  :src="item"
                  :preview-src-list="getImgList(itm.imgList, imgIndex)"
                  style="width: 80px; height: 80px; margin: 0 0 5px 5px"
                ></el-image>
                <i
                  class="el-icon-circle-close"
                  @click="removeImage(index, imgIndex)"
                  style="
                    position: absolute;
                    top: 0;
                    right: 0;
                    cursor: pointer;
                    background-color: #fff;
                    padding: 2px;
                  "
                ></i>
              </div>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                style="margin-left: 15px"
                @click="delInput(index)"
              ></el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button @click="calculate" type="primary">计 算</el-button>
        <el-button type="primary" @click="onEnter">提 交 物 损</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { uploadImage, removeObject } from "@/utils/minio";
import { insertAssessList } from "@/api/system/assessManage";
export default {
  name: "assessDetailsEdit",
  components: {},
  data() {
    return {
      flag: 0,
      form: {},
      isDataChanged: false,
      damageData: [],
      photosToDelete: [],
      newPhotos: [],
      fileName: "",
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  props: {
    detailsVisible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
    itemQuantity: {
      type: Array,
    },
  },
  computed: {},
  watch: {
    formData(e) {
      this.form = {
        ...e,
      };
    },
    itemQuantity(e) {
      this.damageData = e.map((item) => ({
        ...item,
        imgList: item.imgList || [],
      }));
    },
    damageData(e) {
      if (e) {
        this.isDataChanged = true;
      }
    },
  },
  methods: {
    handleFlagChange(value) {
      this.flag = value ? 1 : 0;
    },
    removeImage(projectIndex, imageIndex) {
      const removedImageUrl = this.damageData[projectIndex].imgList.splice(
        imageIndex,
        1
      )[0];
      this.photosToDelete.push(removedImageUrl);
      const newPhotoIndex = this.newPhotos.indexOf(removedImageUrl);
      if (newPhotoIndex !== -1) {
        this.newPhotos.splice(newPhotoIndex, 1);
      }
      // const imageUrlToDelete = this.damageData[projectIndex].imgList[imageIndex];
      // this.deleteImageFromMinio(imageUrlToDelete);
      console.log(
        this.damageData[projectIndex].imgList,
        "Updated image list after deletion",
        this.damageData
      );
    },
    deleteImageFromMinio(imageUrl) {
      const fileName = imageUrl.split("/").pop();
      console.log(fileName);
      removeObject(
        fileName,
        () => {
          console.log("对象已成功删除");
        },
        (err) => {
          console.error("删除对象时出错：", err);
        }
      );
    },
    getImgList(e, index) {
      let arr = [];
      let i = 0;
      for (i; i < e.length; i++) {
        arr.push(e[i + index]);
        if (i + index >= e.length - 1) {
          index = 0 - (i + 1);
        }
      }
      return arr;
    },
    addInput() {
      this.damageData.push({
        damage_project_name: "",
        damage_project_number: "",
        damage_project_price: "",
        total_project_price: "",
        unit: "",
        remarks: "",
        imgList: [],
      });
    },
    Export() {
      this.download(
        "system/export",
        {
          case_number: this.form.case_number,
          flag: this.flag,
        },
        `安徽城投报价表_${new Date().getTime()}.xlsx`
      );
    },
    delInput(index) {
      const deletedDamage = this.damageData.splice(index, 1)[0];
      deletedDamage.imgList.forEach((imageUrl) => {
        this.photosToDelete.push(imageUrl);
      });
      console.log(this.damageData, "CCCCC");
    },
    validateDamageData() {
      console.log(this.damageData);
      for (const item of this.damageData) {
        if (!item.damage_project_name || !item.damage_project_number ||!item.damage_project_price ||
          !item.unit) {
          return false;
        }
      }
      return true;
    },
    handleChangeImg(file, fileList) {},
    uploadImage(request, index) {
      uploadImage({
        file: request.file,
        onSuccess: (only) => {
          this.damageData[index].imgList.push(only.url.split("?")[0]);
          this.newPhotos.push(only.url.split("?")[0]);
          console.log(this.newPhotos, "CCCCCCCCCCCCcc");
        },
        onError: (err) => {
          console.error("Upload failed", err);
        },
      });
    },
    handlePreview(file) {
      // this.dialogImageUrl = file.url;
      // this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      // const fileName = file.name;
      // deleteSurveyImg({
      //   case_number: this.form.case_number,
      //   image_url: fileName,
      // })
      //   .then((response) => {
      //     this.$modal.msgSuccess("删除成功");
      //     this.minioClient.removeObject(this.bucketName, fileName, (err) => {
      //       if (err) {
      //         console.error("删除对象时出错：", err);
      //       } else {
      //         console.log("对象已成功删除", this.bucketName, fileName);
      //       }
      //     });
      //     const index = this.fileList.findIndex(
      //       (item) => item.name === fileName
      //     );
      //     if (index !== -1) {
      //       this.fileList.splice(index, 1);
      //     }
      //   })
      //   .catch((error) => {
      //     console.error("删除图片时出错：", error);
      //   });
    },
    onClose() {
      this.newPhotos.forEach((imageUrl) => {
        this.deleteImageFromMinio(imageUrl);
      });
      this.newPhotos = [];
      this.$emit("onClose");
    },
    calculate() {
      let totalCost = 0;
      this.damageData.forEach((item) => {
        item.total_project_price = (
          item.damage_project_number * item.damage_project_price
        ).toFixed(2);
        totalCost += parseFloat(item.total_project_price);
      });
      // this.damageData.forEach(item => {
      //   const itemTotal = (item.damage_project_number * item.damage_project_price).toFixed(2);
      //   totalCost += parseFloat(itemTotal);
      // });
      this.form.construction_amount = totalCost.toFixed(2);
      this.form.taxes = (totalCost * (this.form.tax_rate / 100)).toFixed(2);
      this.form.total_amount = (
        parseFloat(this.form.construction_amount) + parseFloat(this.form.taxes)
      ).toFixed(2);
      this.isDataChanged = false;
    },
    onEnter() {
      if (!this.validateDamageData()) {
        this.$message.error("请确保每条物损项目都有名称、数量、单位、报价");
        return;
      }
      if (this.isDataChanged || !this.form.total_amount) {
        this.$message.error("请点击计算按钮计算出施工总价");
        return;
      }
      console.log(this.damageData, this.form.case_number, this.form.id);
      insertAssessList({
        case_number: this.form.case_number,
        define_damage_id: this.form.id,
        construction_amount: this.form.construction_amount,
        taxes: this.form.taxes,
        total_amount: this.form.total_amount,
        itemQuantity: this.damageData,
      }).then((response) => {
        this.$modal.msgSuccess("提交成功");
        this.photosToDelete.forEach((imageUrl) => {
          this.deleteImageFromMinio(imageUrl);
        });
        this.photosToDelete = [];
        this.newPhotos = [];
        this.$emit("onEnter");
      });
    },
  },
};
</script>

<style>
.item .el-form-item__label {
  font-size: 21px;
}
.footer {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
